import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: '/api/v1',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    // 添加认证token
    const token = localStorage.getItem('token') || localStorage.getItem('auth_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }



    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    // 对于blob类型的响应，返回完整的response对象
    if (response.config.responseType === 'blob') {
      return response
    }
    return response.data
  },
  error => {
    console.error('响应错误:', {
      status: error.response?.status,
      url: error.config?.url,
      method: error.config?.method,
      data: error.response?.data,
      message: error.message
    })

    // 统一错误处理
    if (error.response?.status === 401) {
      console.warn('401 Unauthorized - 清除认证信息')
      // 处理未授权 - 清除token并跳转到登录页
      localStorage.removeItem('auth_token')
      localStorage.removeItem('auth_user')
      localStorage.removeItem('auth_expires_at')

      // 如果不是登录页面，则跳转到登录页
      if (window.location.pathname !== '/login') {
        window.location.href = `/login?redirect=${encodeURIComponent(window.location.pathname)}`
      }
    } else if (error.response?.status === 500) {
      // 处理服务器错误
      console.error('服务器内部错误')
    } else if (error.code === 'ECONNREFUSED' || error.message.includes('Network Error')) {
      console.error('网络连接错误 - 服务器可能未启动')
    }

    return Promise.reject(error)
  }
)

// 认证API
export const authAPI = {
  // 用户登录
  login: (credentials) => api.post('/auth/login', credentials),

  // 用户注册
  register: (userData) => api.post('/auth/register', userData),

  // 获取当前用户信息
  profile: () => api.get('/auth/profile'),

  // 更新个人资料
  updateProfile: (userData) => api.put('/auth/profile', userData),

  // 修改密码
  changePassword: (passwordData) => api.put('/auth/password', passwordData),

  // 用户登出
  logout: () => api.post('/auth/logout'),

  // 刷新token
  refreshToken: () => api.post('/auth/refresh')
}

// ==================== 客户端管理页面API ====================
export const clientsAPI = {
  // 获取客户端列表
  getClients: (params) => api.get('/clients', { params }),

  // 获取客户端详情
  getClient: (clientId) => api.get(`/clients/${clientId}`),

  // 创建客户端
  createClient: (data) => api.post('/clients', data),

  // 更新客户端
  updateClient: (clientId, data) => api.put(`/clients/${clientId}`, data),

  // 删除客户端
  deleteClient: (clientId) => api.delete(`/clients/${clientId}`),

  // 客户端注册
  registerClient: (data) => api.post('/clients/register', data)
}

export const systemAPI = {
  // 获取系统状态
  getStatus: () => api.get('/status'),

  // 获取系统统计
  getStats: () => api.get('/stats'),

  // 获取系统信息
  getSystemInfo: () => api.get('/system/info'),

  // 更新截图存储路径
  updateStoragePath: (data) => api.put('/system/storage-path', data),

  // 更新录屏存储路径
  updateRecordingStoragePath: (data) => api.put('/system/recording-storage-path', data)
}

// ==================== 仪表板页面API ====================
// 仪表板API - 按功能模块分类
export const dashboardAPI = {
  // 1. 统计卡片数据
  // 获取仪表板统计数据（在线客户端、总客户端、预警客户端、系统运行时间）
  getStats: () => api.get('/dashboard/stats'),

  // 2. 实时预警看板
  // 获取最新预警列表，支持部门和客户端筛选
  getRecentAlerts: (params) => api.get('/dashboard/alerts/recent', { params }),

  // 3. 键盘事件频率趋势图
  // 获取行为趋势数据，支持不同时间范围和对比模式
  getBehaviorTrends: (params) => api.get('/dashboard/behavior/trends', { params }),

  // 4. 鼠标活跃时段热力图
  // 获取鼠标热力图数据，显示不同时间段的活跃度
  getMouseHeatmap: (params) => api.get('/dashboard/mouse/heatmap', { params })
}

// 配置管理API
export const configAPI = {
  // 获取配置列表
  getConfigs: (params) => api.get('/configs', { params }),

  // 获取配置详情
  getConfig: (configId) => api.get(`/configs/${configId}`),

  // 创建配置
  createConfig: (data) => api.post('/configs', data),

  // 更新配置
  updateConfig: (configId, data) => api.put(`/configs/${configId}`, data),

  // 删除配置
  deleteConfig: (configId) => api.delete(`/configs/${configId}`),

  // 应用配置
  applyConfig: (configId, data) => api.post(`/configs/${configId}/apply`, data)
}

// ==================== 预警管理页面API ====================
export const alertsAPI = {
  // 获取预警列表
  getAlerts: (params) => api.get('/alerts', { params }),

  // 获取预警详情
  getAlert: (alertId) => api.get(`/alerts/${alertId}`),

  // 解决预警
  resolveAlert: (alertId, data) => api.put(`/alerts/${alertId}/resolve`, data),

  // 删除预警
  deleteAlert: (alertId) => api.delete(`/alerts/${alertId}`),

  // 批量解决预警
  batchResolveAlerts: (data) => api.post('/alerts/batch-resolve', data),

  // 批量删除预警
  batchDeleteAlerts: (data) => api.post('/alerts/batch-delete', data),

  // 标记所有预警为已读
  markAllAlertsAsRead: () => api.post('/alerts/mark-all-read'),

  // 清空所有预警
  clearAllAlerts: () => api.post('/alerts/clear-all'),

  // 获取预警统计
  getAlertStats: (params) => api.get('/alerts/stats', { params }),

  // 获取预警报表数据
  getAlertReportData: (params) => api.get('/alerts/report-data', { params })
}

// ==================== 远程控制页面API ====================
export const controlAPI = {
  // 启动屏幕共享
  startScreenShare: (clientId) => api.post(`/control/${clientId}/screen/start`),

  // 停止屏幕共享
  stopScreenShare: (clientId) => api.post(`/control/${clientId}/screen/stop`),

  // 发送控制命令（鼠标/键盘控制）
  sendCommand: (clientId, command) => api.post(`/control/${clientId}/command`, command),

  // 手动截图
  takeScreenshot: (clientId, options = {}) => api.post(`/control/${clientId}/screenshot`, {
    quality: options.quality || 80,
    format: options.format || 'png'
  })
}

// ==================== 行为分析页面API ====================
export const behaviorAPI = {
  // 获取行为趋势数据
  getTrends: (params) => api.get('/behavior/trends', { params }),

  // 获取行为热力图数据
  getHeatmap: (params) => api.get('/behavior/heatmap', { params }),

  // 获取行为对比数据
  getCompare: (params) => api.get('/behavior/compare', { params }),

  // 导出行为数据
  exportData: (params) => api.get('/behavior/export', {
    params,
    responseType: 'blob' // 用于文件下载
  }),

  // 获取行为日志数据（详细统计数据）
  getBehaviorLogs: (params) => api.get('/behavior/logs', { params })
}

// ==================== 文件管理页面API ====================
export const filesAPI = {
  // 获取录屏列表
  getRecordings: (params) => api.get('/recordings', { params }),

  // 生成录屏
  generateRecording: (data) => api.post('/recordings/generate', data),

  // 获取截屏列表
  getScreenshots: (params) => api.get('/screenshots', { params }),

  // 删除截图
  deleteScreenshot: (screenshotId) => api.delete(`/screenshots/${screenshotId}`),

  // 批量删除截图
  batchDeleteScreenshots: (data) => api.post('/screenshots/batch-delete', data),

  // 删除录屏
  deleteRecording: (recordingId) => api.delete(`/recordings/${recordingId}`),

  // 批量删除录屏
  batchDeleteRecordings: (data) => api.post('/recordings/batch-delete', data),

  // 下载录屏文件
  downloadRecording: (recordingId) => api.get(`/files/recordings/${recordingId}`, { responseType: 'blob' }),

  // 下载截屏文件
  downloadScreenshot: (screenshotId) => api.get(`/files/screenshots/${screenshotId}`, { responseType: 'blob' }),

  // 获取截屏缩略图
  getScreenshotThumbnail: (screenshotId) => api.get(`/files/screenshots/${screenshotId}/thumbnail`, { responseType: 'blob' })
}

// ==================== 上网管控页面API ====================
export const internetControlAPI = {
  // 网站拦截规则管理
  getWebBlockingRules: (params) => api.get('/internet-control/web-blocking/rules', { params }),
  createWebBlockingRule: (data) => api.post('/internet-control/web-blocking/rules', data),
  updateWebBlockingRule: (ruleId, data) => api.put(`/internet-control/web-blocking/rules/${ruleId}`, data),
  deleteWebBlockingRule: (ruleId) => api.delete(`/internet-control/web-blocking/rules/${ruleId}`),

  // IP拦截规则管理
  getIpBlockingRules: (params) => api.get('/internet-control/ip-blocking/rules', { params }),
  createIpBlockingRule: (data) => api.post('/internet-control/ip-blocking/rules', data),
  updateIpBlockingRule: (ruleId, data) => api.put(`/internet-control/ip-blocking/rules/${ruleId}`, data),
  deleteIpBlockingRule: (ruleId) => api.delete(`/internet-control/ip-blocking/rules/${ruleId}`),

  // 端口拦截规则管理
  getPortBlockingRules: (params) => api.get('/internet-control/port-blocking/rules', { params }),
  createPortBlockingRule: (data) => api.post('/internet-control/port-blocking/rules', data),
  updatePortBlockingRule: (ruleId, data) => api.put(`/internet-control/port-blocking/rules/${ruleId}`, data),
  deletePortBlockingRule: (ruleId) => api.delete(`/internet-control/port-blocking/rules/${ruleId}`),

  // 拦截统计
  getBlockingStats: (params) => api.get('/internet-control/stats/blocking', { params })
}

// ==================== 应用流量管控页面API ====================
export const appTrafficAPI = {
  // 流量规则管理
  getTrafficRules: (params) => api.get('/app-traffic/rules', { params }),
  createTrafficRule: (data) => api.post('/app-traffic/rules', data),
  updateTrafficRule: (ruleId, data) => api.put(`/app-traffic/rules/${ruleId}`, data),
  deleteTrafficRule: (ruleId) => api.delete(`/app-traffic/rules/${ruleId}`),

  // 流量统计
  getTrafficStats: (params) => api.get('/app-traffic/stats', { params }),

  // 应用监控
  getAppTrafficMonitor: (params) => api.get('/app-traffic/monitor', { params })
}

// ==================== 数据安全页面API ====================
export const dataSecurityAPI = {
  // 加密目录管理
  getEncryptedFolders: (params) => api.get('/data-security/encrypted-folders', { params }),
  createEncryptedFolder: (data) => api.post('/data-security/encrypted-folders', data),
  updateEncryptedFolder: (folderId, data) => api.put(`/data-security/encrypted-folders/${folderId}`, data),
  deleteEncryptedFolder: (folderId) => api.delete(`/data-security/encrypted-folders/${folderId}`),

  // USB设备管理
  getUsbDevices: (params) => api.get('/data-security/usb/devices', { params }),
  getUsbWhitelist: (params) => api.get('/data-security/usb/whitelist', { params }),
  addUsbToWhitelist: (data) => api.post('/data-security/usb/whitelist', data),
  removeUsbFromWhitelist: (deviceId) => api.delete(`/data-security/usb/whitelist/${deviceId}`),
  updateUsbPolicy: (data) => api.put('/data-security/usb/policy', data)
}

// ==================== 应用分析页面API ====================
export const appAnalysisAPI = {
  // 获取应用分析数据
  getAppAnalysis: (params) => api.get('/app-analysis', { params }),

  // 获取应用详情
  getAppDetails: (appId) => api.get(`/app-analysis/${appId}`),

  // 终止应用进程
  terminateApp: (appId) => api.post(`/app-analysis/${appId}/terminate`),

  // 获取应用风险评估
  getAppRiskAssessment: (params) => api.get('/app-analysis/risk-assessment', { params })
}

// ==================== AI分析页面API ====================
export const aiAnalysisAPI = {
  // 获取威胁检测数据
  getThreatDetection: (params) => api.get('/ai-analysis/threat-detection', { params }),

  // 获取行为分析数据
  getBehaviorAnalysis: (params) => api.get('/ai-analysis/behavior-analysis', { params }),

  // 获取AI推荐建议
  getRecommendations: (params) => api.get('/ai-analysis/recommendations', { params }),

  // 执行AI分析任务
  runAnalysisTask: (data) => api.post('/ai-analysis/run-task', data),

  // 获取分析报告
  getAnalysisReport: (reportId) => api.get(`/ai-analysis/reports/${reportId}`)
}

// ==================== 用户管理页面API ====================
export const usersAPI = {
  // 获取用户列表
  getUsers: (params) => api.get('/users', { params }),

  // 获取用户详情
  getUser: (userId) => api.get(`/users/${userId}`),

  // 创建用户
  createUser: (data) => api.post('/users', data),

  // 更新用户
  updateUser: (userId, data) => api.put(`/users/${userId}`, data),

  // 删除用户
  deleteUser: (userId) => api.delete(`/users/${userId}`),

  // 重置用户密码
  resetPassword: (userId, data) => api.post(`/users/${userId}/reset-password`, data)
}

// ==================== 部门管理页面API ====================
export const departmentsAPI = {
  // 获取部门列表
  getDepartments: (params) => api.get('/departments', { params }),

  // 获取部门选项（用于下拉选择）
  getDepartmentOptions: () => api.get('/departments/options'),

  // 获取部门详情
  getDepartment: (deptId) => api.get(`/departments/${deptId}`),

  // 创建部门
  createDepartment: (data) => api.post('/departments', data),

  // 更新部门
  updateDepartment: (deptId, data) => api.put(`/departments/${deptId}`, data),

  // 删除部门
  deleteDepartment: (deptId) => api.delete(`/departments/${deptId}`)
}

// ==================== 服务端配置存储API ====================
export const configStorageAPI = {
  // 存储客户端配置（回调接口）
  storeClientConfig: (clientId, configType, config) =>
    api.post(`/config/store/${clientId}/${configType}`, config),

  // 获取客户端所有配置
  getClientAllConfigs: (clientId) =>
    api.get(`/config/client/${clientId}/all`),

  // 获取客户端特定类型配置
  getClientConfig: (clientId, configType) =>
    api.get(`/config/client/${clientId}/${configType}`),

  // 删除客户端配置
  deleteClientConfig: (clientId, configType) =>
    api.delete(`/config/client/${clientId}/${configType}`),

  // 获取所有客户端配置列表
  getAllClientsConfigs: (params) =>
    api.get('/config/clients/all', { params })
}

// 注意：直连客户端API已被移除，现在统一使用服务端策略管理系统
// 所有配置管理通过 configAPI 和 configStorageAPI 进行

// 默认导出主API实例
export default api
